<template>
    <div class="goods-add-form">
        <div class="section">
            <h2 class="section-title">入库基本信息</h2>
            <el-form ref="ruleFormRef" style="max-width: 1200px;margin: 20px;" :model="othwr_order" status-icon
                :rules="rules" label-width="auto" class="demo-ruleForm">
                <el-form-item label="入库单号" prop="othwr_code">
                    <el-input v-model="othwr_order.othwr_code" placeholder="不输入则自动获取编号" />
                </el-form-item>
                <div style="display: flex; justify-content: space-between;">
                    <div style="width: 48%;">
                        <el-form-item label="入库类型" prop="othwr_type" style="margin-bottom: 30px;">
                            <el-select v-model="othwr_order.othwr_type" placeholder="请选择入库类型"
                                @change="handleSelecttype">
                                <el-option v-for="item in options" :key="item.dict_value" :label="item.dict_label"
                                    :value="item.dict_value" class="option-style" />
                            </el-select>
                        </el-form-item>

                        <el-form-item label="入库仓库" prop="warehouse_code" style="margin-bottom: 30px;">
                            <el-select v-model="othwr_order.warehouse_code" placeholder="请选择入库仓库"
                                @change="handleSelectChange">
                                <el-option v-for="item in Weahouse" :key="item.warehouse_code"
                                    :label="item.warehouse_name" :value="item.warehouse_code" />
                            </el-select>
                        </el-form-item>

                        <el-form-item label="供应商昵称" prop="po_Endor_Code" style="margin-bottom: 30px;">
                            <el-select v-model="othwr_order.Vendor_code" placeholder="请选择供应商昵称"
                                :disabled='InsertisDisabledlocation' @change="handleSelectChangeVender">
                                <el-option v-for="item in customerOptonsVender" :key="item.vendor_code"
                                    :label="item.vendor_name" :value="item.vendor_code" />
                            </el-select>
                        </el-form-item>




                    </div>
                    <div style="width: 48%;">
                        <el-form-item label="关联单号" prop="othwr_code_Associated"
                            style="margin-bottom: 30px; width: 100%;">
                            <el-input v-model="othwr_order.othwr_code_Associated" placeholder="请点击输入关联单号" clearable
                                @click="showOrderDialog" readonly class="order-input"
                                style="width: 100%; margin-left: 0px;">
                                <template #append>
                                    <el-button icon="Search" @click="showOrderDialog" />
                                </template>
                            </el-input>
                        </el-form-item>


                        <el-form-item label="入库库区" prop="zone_code" style="margin-bottom: 30px;">
                            <el-select v-model="othwr_order.zone_code" placeholder="请选择入库库区" @change="handleSzone"
                                style="width:100%">
                                <el-option v-for="item in Warhouse_zone" :key="item.zone_code" :label="item.zone_name"
                                    :value="item.zone_code" />
                            </el-select>
                        </el-form-item>


                        <el-form-item label="入库员" prop="othwr_wkeep">
                            <el-cascader v-model="othwr_order.othwr_wkeep" :options="othwr_List"
                                :props="{ emitPath: false, checkStrictly: false }" :show-all-levels="false"
                                placeholder="请选择部门 / 人员" clearable filterable style="width: 100%" />
                        </el-form-item>

                    </div>
                </div>
            </el-form>
        </div>

        <div class="section">
            <h2 class="section-title">入库产品明细</h2>
            <div style="float: left;margin: 10px 0px;">
                <el-button type="primary" @click="productAdd" :disabled='InsertisDisabledlocation'>添加</el-button>
                <el-button @click="productDel" :disabled='InsertisDisabledlocation'>移除</el-button>
            </div>
            <el-table :data="selectedData" border style="width: 100%" :cell-style="{ textAlign: 'center' }"
                :header-cell-style="{
                    textAlign: 'center',
                    background: '#f5f7fa',
                    fontWeight: 'bold',
                    position: 'sticky',
                    top: 0
                }" ref="selectedTable" @selection-change="handleSelectedChange">
                <el-table-column type="selection" width="55" />
                <el-table-column prop="stock_name" label="货品名称" fixed="left" width="100" />
                <el-table-column prop="pro_code" label="货品编号" width="150" />
                <el-table-column prop="pro_brand" label="品牌" width="100" />
                <el-table-column prop="stock_model" label="规格型号" width="100" />
                <el-table-column prop="dict_code" label="单位" width="70">
                    <template #default="scope">
                        <span>{{ measureValue(scope.row.dict_code) }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="location_code" label="入库库位" width="130">
                    <template #default="scope">
                        <el-select v-model="scope.row.location_name" placeholder="选择库位" size="small"
                            :disabled="isDisabledlocation" @change="(val) => locationEndit(val, scope.row)">
                            <el-option v-for="item in Warehouse_location" :key="item.location_code"
                                :label="item.location_name" :value="item.location_code" />
                        </el-select>
                    </template>
                </el-table-column>
                <el-table-column prop="stock_numder" label="当前库存" width="150" />
                <el-table-column prop="pending_numder" label="未入库数量" width="100">
                    <template #default="scope">
                        <span>{{ scope.row.pending_numder || 0 }}</span>
                    </template>
                </el-table-column>


                <el-table-column prop="address" label="入库数量" width="90">
                    <template #default="scope">
                        <el-input v-model="scope.row.sale_qty" style="width: 75px" :precision="2" :min="0"
                            @input="validateSaleQty(scope.row)" @blur="validateQtyAndLocation(scope.row)" />
                    </template>
                </el-table-column>
                <el-table-column prop="address" label="入库单价" width="90">
                    <template #default="scope">
                        <el-input v-model="scope.row.pro_sale_price" style="width: 75px" :precision="2" :min="0" />
                    </template>
                </el-table-column>
                <el-table-column prop="address" label="入库总金额" width="100">
                    <template #default="scope">
                        <span>{{ scope.row.pro_total_amount }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="pro_cost_price" label="成本金额" width="90" />
                <el-table-column prop="address" label="成本合计" width="90">
                    <template #default="scope">
                        <span>{{ scope.row.pro_total_cost }}</span>
                    </template>
                </el-table-column>
            </el-table>
            <div style="height: 40px; line-height: 40px;">
                <div style="display: inline-block; float: left;">合计</div>
                <div style="display: inline-block; float:right">入库总数量：{{ sale_total_qty }}
                    &nbsp;&nbsp;&nbsp; 入库总金额：{{ Number(sale_total_price).toFixed(2) }}
                    &nbsp;&nbsp;&nbsp;入库产品成本总额：{{ Number(cost_total_proce).toFixed(2) }}
                </div>
            </div>
        </div>

        <div class="button-group" style="position: absolute; bottom: 10px; right: 60.8px; display: flex; gap: 10px;">
            <el-button type="primary" @click="handleAdd">保存</el-button>
            <el-button @click="handleClose">关闭</el-button>
        </div>
    </div>

    <!-- 添加产品模态框 -->

    <el-dialog v-model="dialogTableVisible" width="800" title="添加产品">
        <hr>
        <div style="margin: 10px 0px;">
            <div style="float: left;margin: 10px 0px;">
                <el-input v-model="productName" style="width: 240px;margin-right: 20px;" placeholder="请输入货品编号" />
                <el-select v-model="dict_code" placeholder="请选择单位" style="width: 240px">
                    <el-option v-for="item in measureOptios" :key="item.dict_value" :label="item.dict_label"
                        :value="item.dict_value" />
                </el-select>
            </div>
            <div style="float: right;margin: 10px 0px;">
                <el-button @click="productReaslt">重置</el-button>
                <el-button type="primary" @click="productEedit">查询</el-button>
            </div>
        </div>

        <transition name="fade" mode="out-in">
            <div :key="currentPage"> <!-- 添加这个包裹元素 -->
                <el-table ref="multipleTableRef" :data="productData" :cell-style="{ textAlign: 'center' }"
                    :header-cell-style="{
                textAlign: 'center',
                background: '#f5f7fa',
                fontWeight: 'bold',
                position: 'sticky',
                top: 0
            }" @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="55" :selectable="isDisabled" />
                    <el-table-column property="pro_code" label="货品编号" width="180" />
                    <el-table-column property="stock_name" label="货品名称" width="200" />
                    <el-table-column property="stock_model" label="规格型号" />
                    <el-table-column property="dict_code" label="单位">
                        <template #default="scope">
                            <span>{{ measureValue(scope.row.dict_code) }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column property="pro_cost_price" label="入库单价" />
                    <el-table-column property="stock_numder" label="当前库存" />
                </el-table>
                <br>
                <div style="text-align: center;display: flex; justify-content: center;">
                    <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                        :page-sizes="[5, 10, 20, 50]" :small="false" :background="true"
                        layout="total, sizes, prev, pager, next, jumper" :total="pageCount"
                        @size-change="handleSizeChange" @current-change="handleCurrentChange" size="small" />
                </div>
            </div> <!-- 结束包裹元素 -->
        </transition>

        <hr>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogTableVisible = false">取消</el-button>
                <el-button type="primary" @click="handleConfirmSelection">确定</el-button>
            </div>
        </template>
    </el-dialog>



    <!-- 选择关联进货单号模态框 -->
    <el-dialog v-model="orderDialogVisible" width="880px" title="选择关联进货单号" class="order-selection-dialog">
        <!-- 搜索区域 -->
        <div class="dialog-search-area">
            <div class="search-input-group">
                <el-input v-model="orderFilter.orderCode" placeholder="请输入进货单号" clearable prefix-icon="Search"
                    class="search-input" />
                <el-button @click="resetOrderFilter" plain style="margin-left: 12px">
                    <el-icon>
                        <Refresh />
                    </el-icon>重置
                </el-button>
                <el-button type="primary" @click="filterOrders">
                    <el-icon>
                        <Search />
                    </el-icon>查询
                </el-button>
            </div>
        </div>

        <!-- 表格区域 -->
        <transition name="fade" mode="out-in">
            <div :key="orderCurrentPage"> <!-- 添加包裹元素并设置 key -->

                <div class="dialog-table-container">

                    <el-table :data="filteredOrders" border highlight-current-row
                        style="width: 100%; border-radius: 4px;" :cell-style="{ textAlign: 'center', padding: '8px 0' }"
                        :header-cell-style="{
                textAlign: 'center',
                background: 'linear-gradient(to right, #f0f7ff, #e6f7ff)',
                fontWeight: 600,
                color: '#1a73e8',
                fontSize: '14px',
                height: '48px'
            }" :row-style="{ height: '48px' }" @selection-change="handleOrderSelectionChange"
                        @row-click="handleOrderSelect">
                        <el-table-column type="selection" width="60" align="center" />
                        <el-table-column prop="othwr_code" label="进货单号" width="200">
                            <template #header>
                                <div class="column-header">
                                    <el-icon>
                                        <Document />
                                    </el-icon>单号
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column prop="warehouse_name" label="仓库" width="200">
                            <template #header>
                                <div class="column-header">
                                    <el-icon>
                                        <OfficeBuilding />
                                    </el-icon>仓库
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column prop="startdate" label="日期" width="200">
                            <template #header>
                                <div class="column-header">
                                    <el-icon>
                                        <Calendar />
                                    </el-icon>日期
                                </div>
                            </template>
                            <template #default="{ row }">
                                <div class="date-cell">
                                    {{ formatDate(row.startdate) }}
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column prop="create_by" label="创建人" width="200">
                            <template #header>
                                <div class="column-header">
                                    <el-icon>
                                        <User />
                                    </el-icon>创建人
                                </div>
                            </template>
                        </el-table-column>

                    </el-table>
                </div>

                <!-- 分页区域 -->
                <div class="dialog-pagination">
                    <el-pagination v-model:current-page="orderCurrentPage" v-model:page-size="orderPageSize"
                        :page-sizes="[5, 10, 20, 50]" :small="true" :background="true"
                        layout="total, sizes, prev, pager, next, jumper" :total="orderTotalCount"
                        @size-change="handleOrderSizeChange" @current-change="handleOrderCurrentChange" />
                </div>
            </div> <!-- 结束包裹元素 -->
        </transition>

        <!-- 底部操作区域 -->
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="orderDialogVisible = false" size="medium" plain>
                    <el-icon>
                        <Close />
                    </el-icon>取消
                </el-button>
                <el-button type="primary" size="medium" @click="confirmOrderSelection"
                    :disabled="selectedOrders.length === 0">
                    <el-icon>
                        <Check />
                    </el-icon>确定 ({{ selectedOrders.length }})
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted, inject, watch, toRaw } from 'vue'
import dayjs from 'dayjs'
import axios from 'axios'
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { debounce } from 'lodash';
import { computed } from 'vue';

// 入库类型
const options = ref([])
// 仓库库区
const Warhouse_zone = ref([]);
// 库位
const Warehouse_location = ref([]);



const customerOptonsVender = ref([])//供应商信息

let othwrAdd = {
    othwr_type: "", // 入库类型
    othwr_code: "", // 入库单号
    othwr_code_Associated:"", // 关联单号
    othwr_wkeep: "", // 入库员
    othwr_time: dayjs().format('YYYY-MM-DDTHH:mm:ss.SSSZ'), // R库时间
    othwr_status: 1, // 入库状态
    warehouse_code: "",
    warehouse_name: "",
    zone_code: "",
    zone_name: "",
    othwr_audit_by: "", // 审核人
    othwr_audit_time: "", // 审核时间
    othwr_audit_statua: 0, // 审核状态
    del_flag: '0', // 删除状态
    create_by: localStorage.getItem('userLName'), // 创建人
    create_time: dayjs().format('YYYY-MM-DDTHH:mm:ss.SSSZ'), // 创建时间 
    Vendor_code:"",
    Vendor_name:"",
}

// 模态对象
const othwr_order = reactive({ ...othwrAdd })


const zoneCache = ref({}); // 缓存仓库对应的库区
const locationCache = ref({}); // 缓存库区对应的库位



const ruleFormRef = ref(null)
const rules = reactive({
    
    /* ------- 入库类型 ------- */
    othwr_type: [
        { required: true, message: '请选择入库类型', trigger: 'change' }
    ],

    /* ------- 入库仓库 ------- */
    warehouse_code: [
        { required: true, message: '请选择入库仓库', trigger: 'change' }
    ],

    /* ------- 入库库区 ------- */
    zone_code: [
        { required: true, message: '请选择入库库区', trigger: 'change' }
    ],

  

    /* ------- 供应商 ------- */
    Vendor_code: [
        {
            required: true,
            validator(_rule, value, callback) {
                // 非期初入库时必须选供应商
                if (othwr_order.othwr_type !== '5' && !value) {
                    callback(new Error('请选择供应商'));
                } else {
                    callback();
                }
            },
            trigger: 'change'
        }
    ],
    othwr_wkeep: [
        { required: true, message: '请选择入库员', trigger: 'change' }
    ]
});

// 仓库名称查询
const Weahouse = ref([]);

const userOptions = ref([])
const deptOptions = ref([])
const customerOptons = ref([])
const customer_name = ref("")
const dialogTableVisible = ref(false)
const productData = ref([])
const currentPage = ref(1)
const pageSize = ref(5)
const pageCount = ref(0)

const productName = ref("")
const dict_code = ref("0")

const measureOptios = ref([])
const multipleTableRef = ref(null); // 表格引用

const selectedProducts = ref([]); // 存储选中的产品

const selectedTable = ref(null); // 表格引用
const selectedRows = ref([]); // 存储选中的数据
const selectedData = ref([]); // 最终确认选择的数据
const attributeOptios = ref([])
const sale_total_qty = ref(0) // 记录销售总数
const sale_total_price = ref(0) // 记录销售总额
const cost_total_proce = ref(0) // 记录产品成本总额
const router = useRouter()

const SweetAsync = ref({}); // 关联单号的查询


var isDisabledlocation = ref();//下拉框禁用

//控制添加产品的禁用和移出产品的禁用
var InsertisDisabledlocation = ref();//下拉框禁用

watch(selectedData, (newVal) => {
    // 每次计算时清空累加
    sale_total_qty.value = 0
    sale_total_price.value = 0
    cost_total_proce.value = 0
    newVal.forEach(row => {
        if (isNaN(Number(row.sale_qty))) {
            ElMessage.warning('入库数量必须是数字');
            row.sale_qty = 0;
        }

        // 验证销售单价
        if (isNaN(Number(row.pro_sale_price))) {
            ElMessage.warning('入库单价必须是数字');
            row.pro_sale_price = 0;
        }

        //期初入库不用进行判断
        if (PdSelcr.value!=5){
        // if (row.sale_qty > row.stock_numder) {
        //     ElMessage.warning('入库数量不能大于当前库存');
        //     row.sale_qty = row.stock_numder
        // }

            if (row.sale_qty > row.pending_numder) {
            ElMessage.warning('入库数量不能大于未入库数量');    
            row.sale_qty = row.pending_numder
        }
    }
       //监听事件 盘盈入库要全部入库
    

        row.pro_total_amount = Number((row.sale_qty || 0) * (row.pro_sale_price || 0)).toFixed(2);
        row.pro_total_cost = Number((row.sale_qty || 0) * (row.pro_cost_price || 0)).toFixed(2);

        sale_total_qty.value += Number(row.sale_qty)
        sale_total_price.value += Number(row.pro_total_amount)
        cost_total_proce.value += Number(row.pro_total_cost)
    });
}, { deep: true });

//判断是否提示盘盈入库要全部入库
var PdSelcrPSwer = ref(0);
// 盘盈入库验证方法
const validateSaleQty = (row) => {
    if (PdSelcr.value === 3) {
        if (row.sale_qty != row.pending_numder && row.sale_qty != 0) {
        //    ElMessage.warning("盘盈入库要全部入库");
           // row.sale_qty = 0;
            PdSelcrPSwer.value = 1;
        }else{
            PdSelcrPSwer.value = 2;
        }
    }
};


// 关联单号对话框相关状态
const orderDialogVisible = ref(false);
const selectedOrders = ref([]);
const selectedOrder = ref(null); // 存储单选订单
const orderFilter = reactive({
    orderCode: ""
});
//获取详细信息
//const cpSelectData=ref([]);


// 分页相关
const orderCurrentPage = ref(1);
const orderPageSize = ref(5);
const orderTotalCount = ref(0);

// 格式化日期
const formatDate = (dateString) => {
    if (!dateString) return '';
    const date = new Date(dateString);
    return date.toLocaleDateString();
};

// 获取状态文本
const getStatusText = (status) => {
    switch (status) {
        case 0: return "未入库";
        case 1: return "已入库";
        case 2: return "部分入库";
        default: return "未知状态";
    }
};

// 获取状态标签类型
const getStatusTagType = (status) => {
    switch (status) {
        case 0: return "warning";
        case 1: return "success";
        case 2: return "info";
        default: return "";
    }
};

// 过滤订单数据
const filteredOrders = computed(() => {
    // 确保始终操作数组
    const orders = Array.isArray(SweetAsync.value) ? SweetAsync.value : [];
    if (!orderFilter.orderCode) return orders;

    return orders.filter(order =>
        order.othwr_code && typeof order.othwr_code === 'string'
            ? order.othwr_code.includes(orderFilter.orderCode)
            : false
    );
});






// 处理订单选择变化（多选）
const handleOrderSelectionChange = async(val) => {
    selectedOrders.value = val;
};

// 处理行点击（单选）
const handleOrderSelect = (order) => {
    selectedOrder.value = order;
};

// 重置筛选条件
const resetOrderFilter = () => {
    orderFilter.orderCode = "";
    filterOrders();
};

// 确认选择订单 进行赋值
  function confirmOrderSelection(){
        //每次进来清空
        selectedData.value = []


    // 优先使用单选选择
    if (selectedOrder.value) {
        othwr_order.othwr_code_Associated = selectedOrder.value.othwr_code;
        orderDialogVisible.value = false;
        return;
    }

    // 如果没有单选选择，检查多选
    if (selectedOrders.value.length === 0) {
        ElMessage.warning('请先选择一条订单记录');
        return;
    }

    // 确保只选择一个订单
    if (selectedOrders.value.length > 1) {
        ElMessage.warning('只能选择一个关联单号');
        return;
    }

    othwr_order.othwr_code_Associated = selectedOrders.value[0].othwr_code;

   

    othwr_order.warehouse_name = selectedOrders.value[0].warehouse_name;
    othwr_order.warehouse_code = selectedOrders.value[0].warehouse_code;

    

    
     
    //更新下拉框的值--库区
    axios.get("http://localhost:5181/api/Db_warehouse_zone/warehouse_zone", {
        params: {
            warehouse_code: othwr_order.warehouse_code
        }, headers: {
            authorization: `Bearer ${localStorage.getItem('token')}`
        }
    }).then((result) => {
        Warhouse_zone.value = result.data;
    })


      if (PdSelcr.value==2){
          //调拨入库
          const kccode = selectedOrders.value[0].warehouse_out_code;
        
          //更新产品的信息
          axios.get("http://localhost:5181/api/Inv_trf/Inv_trf_SelectDetail", {
              params: {
                  trf_code: selectedOrders.value[0].othwr_code
              },
              headers: {
                  authorization: `Bearer ${localStorage.getItem('token')}`
              }
          }).then(async (result) => {
             
              // 创建临时数组存储产品数据
              const tempData = [];

              // 遍历每个产品获取库存
              for (const item of result.data) {
                  // 获取当前产品的库存
                  const stockNumber = await StockSelect(
                      kccode,  // 仓库编码
                      item.pro_code,
                     item.stock_entry_no        // 产品编码
                  );

                  // 构建产品对象
                  tempData.push({
                      ...item,
                      stock_name: item.pro_name,   // 字段转换--仓库名称
                      stock_model: item.pro_model, // 字段转换--规格型号
                      dict_code: item.unitmeas_id, // 字段转换--单位
                      sale_qty: 0, // 未入库数量
                      Othwrproddtl_numder: 0,
                      stock_numder: stockNumber,   // 库存数量
                      pro_sale_price: item.pro_sale_price || 0, // 入库单价
                      pro_cost_price: item.pro_cost_price || 0,// 入库成本价
                      pro_total_amount: 0,         // 初始化入库总金额
                      pro_total_cost: 0,           // 初始化成本合计
                  });

              }


              // 赋值给selectedData
              selectedData.value = tempData;
              //下拉框禁用
              // isDisabledlocation.value = true;

          }).catch((err) => {
              console.error("获取产品明细失败:", err);
              ElMessage.error('获取产品明细失败');
          });
          
      } else if (PdSelcr.value==3){
        //盘盈入库
          othwr_order.zone_name = selectedOrders.value[0].zone_name;
          othwr_order.zone_code = selectedOrders.value[0].zone_code;
     

          //更新库位的信息
          getWarehouse_location(othwr_order.zone_code);

            //更新产品信息
     axios.get("http://localhost:5181/api/Inv_Qty/Inv_Qty_SelectMainDetail",{
            params:{
                  qty_code: selectedOrders.value[0].othwr_code
            },
            headers: {
                authorization: `Bearer ${localStorage.getItem('token')}`
            }
          }).then(async(res)=>{
            //盘盈入库--获取产品信息


            // 创建临时数组存储产品数据
            const tempData = [];

            for(const item of  res.data){
                // 获取当前产品的库存
                const stockNumber = await StockSelect(
                    othwr_order.warehouse_code,
                    item.pro_code,
                    item.stock_entry_no          // 产品编码
                );
                //构建产品对象
                tempData.push({
                    ...item,
                    stock_name: item.pro_name,   // 字段转换--仓库名称
                    stock_model: item.pro_model, // 字段转换--规格型号
                    dict_code: item.unitmeas_id, // 字段转换--单位
                    sale_qty: 0, // 未入库数量
                    Othwrproddtl_numder: 0,
                    pending_numder: item.proddti_profit,
                    stock_numder: stockNumber,   // 库存数量
                    pro_sale_price: item.pro_sale_price || 0, // 入库单价
                    pro_cost_price: item.pro_cost_price || 0,// 入库成本价
                    pro_total_amount: 0,         // 初始化入库总金额
                    pro_total_cost: 0,           // 初始化成本合计
            });

              

        }
              selectedData.value = tempData;
              //console.log(selectedData.value);
          }).catch((err)=>{
            console.error(err);
          });
      } else if (PdSelcr.value == 5){
       
            //期初入库--没有任何操作--可以打开模态框

      }
    orderDialogVisible.value = false;
};



//期初库存--查询出来全部的商品
function Inv_stock_numfer(product_code){
    return axios.get("http://localhost:5181/api/Inv_Stock/Get_inv_stock_totalnumber",{
        params:{
            Pro_code:product_code
        },headers:{
            authorization:`Bearer ${localStorage.getItem('token')}`
        }
    })
}


//根据仓库编码和产品编码查询库存信息
function StockSelect(Waarehouse_code, Pro_code, stock_entry_no) {

    return axios.get("http://localhost:5181/api/Inv_Stock/Getinv_stock_XQ", {
        params: {
            weahouse_code: Waarehouse_code,
            por_code: Pro_code,
            stock_entry_no: stock_entry_no
        },
        headers: {
            authorization: `Bearer ${localStorage.getItem('token')}`
        }
    }).then((res) => {
        return res.data;
    }).catch((res) => {
        console.log(res);
    })
}

//查询供应商
function getCustomerVender() {
    axios.get("http://localhost:5181/api/Values/Pinv_VendorWhere", {
        params: {
            Vendor_name: customer_name.value
        }, headers: {
            authorization: `Bearer ${localStorage.getItem('token')}`
        }
    }).then((result) => {
        customerOptonsVender.value = result.data
    }).catch((err) => {
        console.info(err)
    });
}
// 点击保存按钮
async function handleAdd() {
    
    if (PdSelcrPSwer.value==1){
        ElMessage.warning("盘盈数量要全部入库");
        return;
    }
    const valid = await ruleFormRef.value.validate().catch(() => false);
    if (!valid) {
        ElMessage.warning('请先完善必填项');
        return;
    }


    try {
        // 1. 生成入库单号
        await obtainCode();
        console.log("生成的入库单号:", othwr_order.othwr_code);



        // // 2. 计算入库状态（放在保存主表之前）
        // let allCompleted = true;
        // let anyPartial = false;

        // // 3遍历所有明细项计算状态
        // for (const item of selectedData.value) {
        //     const qty = Number(item.sale_qty) || 0;
        //     const inventoryQty = Number(item.inventory_numder) || 0;

        //     if (qty < inventoryQty) {
        //         anyPartial = true;
        //         allCompleted = false;
        //     } else if (qty !== inventoryQty) {
        //         allCompleted = false;
        //     }
        // }

        // //4 设置入库状态
        // if (allCompleted) {
        //     othwr_order.othwr_status = 1; // 全部入库
        // } else if (anyPartial) {
        //     othwr_order.othwr_status = 2; // 部分入库
        // } else {
        //     othwr_order.othwr_status = 0; // 未入库
        // }

        othwr_order.othwr_status = 0;

        // 5. 保存主表信息
        const mainResponse = await axios.put(
            "http://localhost:5181/api/Inv_othwr/Inv_othwr_Insert",
            othwr_order,
            { headers: { authorization: `Bearer ${localStorage.getItem('token')}` } }
        );

        if (mainResponse.data > 0) {
            ElMessage.success("保存成功");

            // 6. 获取主表ID
            const id = await Select_othwr_id();
          

            // 7. 转换明细数据
            const detailList = selectedData.value.map(item => ({
                Othwr_id: id,
                Pro_name: item.stock_name,
                Pro_code: item.pro_code,
                Pro_brand: item.pro_brand,
                unitmeas_id:String(item.dict_code),
                Othwrproddtl_numder: Number(item.sale_qty),
                Inventory_numder: Number(item.inventory_numder) || 0,
                Pro_model: item.stock_model,
                othwrproddtl_time: dayjs().format('YYYY-MM-DDTHH:mm:ss.SSSZ'),
                othwrproddtl_yuan: localStorage.getItem('userLName'),
                location_code: item.location_code ? item.location_code.replace(/\r\n/g, "") : "",
                location_name: item.location_name,
                pro_cost_price: Number(item.pro_cost_price),
                pro_sale_price: Number(item.pro_sale_price),
                stock_entry_no: String(item.stock_entry_no || "0"), // 关键修复：转为字符串 
                Vendor_code:othwr_order.Vendor_code,
                Vendor_name:othwr_order.Vendor_name
            }));
            // 8. 保存明细
            await Inv_othproddetails_add(detailList);

            console.log("初期入库:",detailList)
            
            //添加完成之后清空数据--产品数据
            selectedData.value = [];
            
           //添加完成之后
            clearForm();


            isDisabledlocation.value = false;

            //返回主界面
            router.push('/main/Inv/OtherWarehouseReceipts');
        } else {
            ElMessage.error("主表保存失败");
        }
    } catch (error) {
        console.error("保存出错:", error);
        ElMessage.error("保存过程中发生错误");
    }
}


// 清空表单数据和下拉框选项的方法
function clearForm() {
   
   

    // 清空关联单号
    othwr_order.othwr_code_Associated = "";

    // 清空其他表单数据
    othwr_order.othwr_code = "";
    othwr_order.othwr_type = "";
    othwr_order.warehouse_code = "";
    othwr_order.warehouse_name = "";
    othwr_order.zone_code = "";
    othwr_order.zone_name = "";
    
}


//添加详细表 
function Inv_othproddetails_add(detailList){
    axios.put(" http://localhost:5181/api/Inv_othwr/Inv_othproddetails", detailList, {
        headers: {
            authorization: `Bearer ${localStorage.getItem('token')}`
        }
    }).then((res) => {
      
    }).catch((res) => {
        console.log(res)
    })
}

// 根据编号查询ID
function Select_othwr_id() {
    return new Promise((resolve, reject) => {
        axios.get("http://localhost:5181/api/Inv_othwr/InvOthwrproddtlSelect_id", {
            params: {
                otgwr_code: othwr_order.othwr_code // 修正参数名
            },
            headers: {
                authorization: `Bearer ${localStorage.getItem('token')}`
            }
        }).then((res) => {
            resolve(res.data); // 正确返回数据
        }).catch((error) => {
            console.error("获取ID失败:", error);
            reject(error);
        });
    });
}

// 获取编号
async function obtainCode() {
    try {
        const result = await axios.get("http://localhost:5181/api/DJBH/DJBH", {
            params: { en_code: 9 },
            headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
        });
        othwr_order.othwr_code = result.data;
      
    } catch (err) {
        console.error("生成单号失败:", err);
        throw err;
    }
}




// 分页大小变化
const handleOrderSizeChange = (val) => {
    orderPageSize.value = val;
    filterOrders();
};

// 当前页码变化
const handleOrderCurrentChange = (val) => {
    orderCurrentPage.value = val;
    filterOrders();
};

// 过滤订单（带分页）
const filterOrders = () => {
    //if判断是盘盈的总数量,还是调拨的数量
    if (PdSelcr.value==2) {
        axios.get("http://localhost:5181/api/Inv_trf/Inv_Select_MainSelect_Count", {
            params: {

                code: orderFilter.orderCode
            }
        }).then(response => {
            orderTotalCount.value = response.data;
        }).catch(error => {
            console.error(error);
            ElMessage.error('获取订单数据失败');
        });
    }else if(PdSelcr.value==3){
        //盘盈入库
        axios.get("http://localhost:5181/api/Inv_trf/Inv_Select_MainSelect_Count", {
            params: {

                code: orderFilter.orderCode
            }
        }).then(response => {
            orderTotalCount.value = response.data;
        }).catch(error => {
            console.error(error);
            ElMessage.error('获取订单数据失败');
        });
}
        
    }


//判断加载明细表
var PdSelcr=ref(0);



// 获取订单列表数据--判断
const showOrderDialog = async() => {
    selectedOrders.value = [];
    selectedOrder.value = null;
    orderFilter.orderCode = "";

    switch (othwr_order.othwr_type) {
        // 调拨入库
        case "2":
            PdSelcr.value = 2;
            //如果是调拨入库的禁用添加
            InsertisDisabledlocation.value = true;
        
            // 创建临时数组存储产品数据
            const transformOthwrData = [];
        
           await axios.get("http://localhost:5181/api/Inv_trf/Inv_Select_MainSelect", {
                params: {
                    code: orderFilter.orderCode,
                    currentPage: orderCurrentPage.value,
                    pageSize: orderPageSize.value
                },
                headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then(result => {
                SweetAsync.value = result.data; 
                //数据类型进行转换
                for (const item of result.data){
                
                    transformOthwrData.push({
                        othwr_code: item.trf_code,
                        warehouse_name: item.warehouse_enter_name,
                        create_by: item.create_by,//创建人
                        startdate:item.trf_startdate,
                        warehouse_code:item.warehouse_enter_code,
                        warehouse_out_code:item.warehouse_out_code,
                        stock_entry_no:item.stock_entry_no,
                    })
                
                }

                SweetAsync.value = transformOthwrData;
               
              
                //显示关联模态框
                orderDialogVisible.value = true;
            }).catch(error => {
                console.log(error);
            });
            filterOrders();
            break;
        case"3"://盘盈入库
            
            PdSelcr.value = 3;
            //如果是盘盈入库的禁用添加
            InsertisDisabledlocation.value = true;

            // 创建临时数组存储产品数据
            const transformOthwrDataPd = [];


           await axios.get("http://localhost:5181/api/Inv_Qty/Inv_Qty_MainSelect", {
                params: {
                    code: orderFilter.orderCode,
                    currentPage: orderCurrentPage.value,
                    pageSize: orderPageSize.value
                },
                headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then(result => {
                SweetAsync.value = result.data;
                //数据类型进行转换
                for (const item of result.data) {

                    transformOthwrDataPd.push({
                        othwr_code: item.qty_code,
                        warehouse_name: item.warehouse_name,
                        warehouse_code: item.warehouse_code,
                        create_by: item.create_by,//创建人
                        startdate:item.qty_startdate,
                        zone_code: item.zone_code,
                        zone_name: item.zone_name,
                        //stock_entry_no: item.stock_entry_no,
                    })

                }
                SweetAsync.value = transformOthwrDataPd;
                //显示关联模态框
                orderDialogVisible.value = true;
            }).catch(error => {
                console.log(error);
            });


            filterOrders();
        break;
       case "5":
          PdSelcr.value = 5;
            
          break;
    }
};








// 防抖函数0.5秒后进行查询
const getCustomerDebounced = debounce(getCustomer, 500);

// 查询客户信息
function getCustomer() {
    axios.get("http://localhost:5181/api/Sinv_Customer/Sinv_CustomerByName", {
        params: {
            name: customer_name.value
        }, headers: {
            authorization: `Bearer ${localStorage.getItem('token')}`
        }
    }).then((result) => {
        customerOptons.value = result.data
    }).catch((err) => {
        console.info(err)
    });
}

// 把二维数据转换为结构数据
const convertToTreeOptions = (items) => {
    return items.map(item => ({
        value: item.dept_id,
        label: item.dept_name,
        children: item.children && item.children.length > 0
            ? convertToTreeOptions(item.children)
            : []
    }))
}

// 获取下拉选项数据
function getClassify() {
    axios.get("http://localhost:5181/api/Dict/Get_Dict_Datas", {
        params: {
            dict_type: "sys_inv_othwr"
        }, headers: {
            authorization: `Bearer ${localStorage.getItem('token')}`
        }
    }).then((result) => {
        options.value = result.data
    }).catch((err) => {
        console.info(err)
    });
}

// 选择入库事件触发
const handleSelectChange = (warehouse_code) => {
  const item = Weahouse.value.find(i => i.warehouse_code === warehouse_code);
  othwr_order.warehouse_name = item?.warehouse_name;

  if (zoneCache.value[warehouse_code]) {
    Warhouse_zone.value = zoneCache.value[warehouse_code];
  } else {
    axios.get("http://localhost:5181/api/Db_warehouse_zone/warehouse_zone", {
      params: { warehouse_code },
      headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
    }).then(res => {
      zoneCache.value[warehouse_code] = res.data;
      Warhouse_zone.value = res.data;
    });
  }
};
//选择供应商
const handleSelectChangeVender=(value)=>{
    const Vendor_name=customerOptonsVender.value.find(item=>item.vendor_code===value)
    othwr_order.Vendor_name=Vendor_name.vendor_name;
  
}


// 增加产品数据缓存对象
const productDetailCache = ref({});

const debounceSearch = debounce((fn) => fn(), 500);

// 入库类型选择事件触发

const handleSelecttype = (value) => {
    const oldType = othwr_order.othwr_type; // 保存旧类型

    // 1. 保存当前类型的产品数据到缓存
    if (oldType) {
        productDetailCache.value[oldType] = [...selectedData.value];
    }

    const selectedItem = options.value.find(item => item.dict_value == value);
    othwr_order.othwr_type = selectedItem.dict_value;

    /* 1. 清空关联单号 */
    orderFilter.orderCode = "";
    othwr_order.othwr_code_Associated = "";

    /* 2. 清空仓库/库区/库位及其下拉选项 */
    othwr_order.warehouse_code = "";
    othwr_order.warehouse_name = "";
    othwr_order.zone_code = "";
    othwr_order.zone_name = "";
    Warhouse_zone.value = [];          // 库区下拉框
    Warehouse_location.value = [];     // 库位下拉框

    /* 3. 清空产品明细表 & 弹窗产品数据 */
    productData.value = [];

    /* 4. 根据类型做特殊处理 */
    PdSelcr.value = value; // 更新当前类型

    // 设置是否禁用添加按钮
    InsertisDisabledlocation.value = value !== '5'; // 非期初入库禁用添加

    // 尝试从缓存恢复产品数据
    if (productDetailCache.value[value]?.length > 0) {
        selectedData.value = [...productDetailCache.value[value]];
    } else {
        // 期初入库没有缓存则重新查询
        if (value == 5) {
            // 5. 优化期初入库产品查询逻辑 - 重置查询条件
            productName.value = ""; // 重置货品编号查询条件
            dict_code.value = "0"; // 重置单位查询条件
            currentPage.value = 1; // 重置分页页码
            productFill();
            productCount();
        } else {
            // 其他类型没有缓存则清空
            selectedData.value = [];
        }
    }
};

// 选择入库库区的时触发
const handleSzone = (value) => {
    const selectedItemzone = Warhouse_zone.value.find(item => item.zone_code == value)
    othwr_order.zone_name = selectedItemzone.zone_name;
    //下拉框禁用解除
    isDisabledlocation.value = false;
    //获取库位
    getWarehouse_location(value);
}

//更新库位的信息
function getWarehouse_location(value) { 
    
    axios.get("http://localhost:5181/api/Db_warehouse_location/warehouse_location", {
        params: {
            zone_code: value
        }, headers: {
            authorization: `Bearer ${localStorage.getItem('token')}`
        }
    }).then((result) => {
        Warehouse_location.value = result.data;
    }).catch((err) => {
        console.info(err)
    })
}


//选择入库库位的触发事件
const locationEndit = async(value, row) => {
    // 1. 直接更新当前行的数据
    row.location_code = value; // 确保location_code更新
    const selectedItem = Warehouse_location.value.find(item => item.location_code === value);
    row.location_name = selectedItem ? selectedItem.location_name : '';

    if (!selectedItem) {
        ElMessage.error('未找到该库位信息');
        return;
    }

    
    //如果是期初入库的话,不是获取总库存,根据当前选择的库位获取库存
    if (PdSelcr.value==5){
        const Numder = await Stock_select_numder(
            othwr_order.warehouse_code,
            othwr_order.zone_code,
            row.location_code,
            row.pro_code
        );
       
        row.stock_numder = Numder;
    }




    // 2. 获取可用容量
    const availableCapacity = selectedItem.location_available_capacity;

   // 3. 计算当前库位的入库总量
    const totalQty = selectedData.value
        .filter(item => item.location_code === value)
        .reduce((sum, item) => sum + Number(item.sale_qty || 0), 0);

    // 4. 检查容量是否足够
    if (totalQty > availableCapacity) {
        ElMessage.error(`库位容量不足！可用：${availableCapacity}，已分配：${totalQty}`);
        // 5. 回滚选择
        row.location_code = '';
        row.location_name = '';
    }
};



const validateQtyAndLocation = async (row) => {
   

    // 3. 校验是否选择库位
    if (!row.location_code) {
        ElMessage.warning('请先选择入库库位');
        return;
    }

    // 4. 获取库位容量
    const selectedItem = Warehouse_location.value.find(
        item => item.location_code === row.location_code
    );
    if (!selectedItem) {
        ElMessage.error('未找到该库位信息');
        return;
    }

    const maxCapacity = selectedItem.location_available_capacity || 0;

    //5. 计算当前库位已分配数量（包括当前行）
    const totalQty = selectedData.value
        .filter(item => item.location_code === row.location_code)
        .reduce((sum, item) => sum + Number(item.sale_qty || 0), 0);

    if (totalQty > maxCapacity) {
        ElMessage.error(
            `库位容量不足！最大容量：${maxCapacity}，当前已分配：${totalQty}`
        );
        row.sale_qty = 0; // 或 row.sale_qty = maxCapacity - (totalQty - row.sale_qty)
    }
};


async function Stock_select_numder(warehouse_code, zone_code, location_code, pro_code) {
    try {
        const response = await axios.get("http://localhost:5181/api/Inv_Stock/int_stock_numder", {
            params: {
                warehouse_code,
                zone_code,
                location_code,
                pro_code
            },
            headers: {
                authorization: `Bearer ${localStorage.getItem('token')}`
            }
        });
        return response.data; // ✅ 只返回 data 部分（即 880）
    } catch (error) {
        console.error("请求失败:", error);
        return 0; // 失败时返回默认值
    }
}



function productAdd() {
    dialogTableVisible.value = true
    // productFill();
    // productCount();
}

// 移除选中的table控件数据
const productDel = () => {
    if (selectedRows.value.length === 0) {
        ElMessage.warning('请先选择要移除的数据');
        return;
    }

    const selectedCodes = selectedRows.value.map(item => item.pro_code);
    selectedData.value = selectedData.value.filter(
        item => !selectedCodes.includes(item.pro_code)
    );

    if (selectedTable.value) {
        selectedTable.value.clearSelection();
    }

    selectedRows.value = [];
};

// 分页查询产品库存信息
function productFill() {
   
    //alert("期初入库"+PdSelcr.value)
    //alert("期初入库")
    //判断默认是查询库存里面的数据--如果dSelcr.value为5的话,要去产品中信息查询数据
    if (PdSelcr.value==5){
      
        axios.get("http://localhost:5181/api/Db_Product/Get_Products_Other",{
            params:{
                procode: productName.value,
                Measure_id: dict_code.value,
                currentPage: currentPage.value,
                pageSize: pageSize.value
            },
            headers:{
                authorization: `Bearer ${localStorage.getItem('token')}`
            }
        }).then(async(res)=>{
            // 创建临时数组存储产品数据
            const transformOthwrDataPd = [];
             
            for (const item of res.data) { 
          //获取产品总库存
                const stockNumberResponse = await Inv_stock_numfer(item.pro_code);
                const stockNumber = stockNumberResponse.data; // 提取 data 属性的值
                
                transformOthwrDataPd.push({
                    ...item,
                    pro_code: item.pro_code,
                    stock_name:item.pro_name,
                    stock_model: item.pro_model,
                    dict_code: item.measure_id,
                    pro_cost_price: item.pro_cost_price,
                    stock_numder: stockNumber
                });
            }
            //赋值
            productData.value = transformOthwrDataPd;

        }).catch((err)=>{ 
            console.info(err);
        });
    }else{
        
        axios.get("http://localhost:5181/api/Db_warehouse/GetInv_Stock", {
            params: {
                productName: productName.value,
                dict_code: dict_code.value,
                currentPage: currentPage.value,
                pageSize: pageSize.value
            }, headers: {
                authorization: `Bearer ${localStorage.getItem('token')}`
            }
        }).then((result) => {
            productData.value = result.data
        }).catch((err) => {
            console.info(err)
        });

    }
}

// 查询产品库存总数
function productCount() {
    //判断默认是查询库存里面的数据--如果dSelcr.value为5的话,要去产品中信息查询数据
    if (PdSelcr.value == 5) {
        axios.get("http://localhost:5181/api/Db_Product/ProductCount_Other", {
            params: {
                procode: productName.value,
                Measure_id: dict_code.value
            }, headers: {
                authorization: `Bearer ${localStorage.getItem('token')}`
            }
        }).then((result) => {
            pageCount.value = result.data
        }).catch((err) => {
            console.info(err)
        });
    }else{

        axios.get("http://localhost:5181/api/Db_warehouse/Inv_StockCount", {
            params: {
                productName: productName.value,
                dict_code: dict_code.value
            }, headers: {
                authorization: `Bearer ${localStorage.getItem('token')}`
            }
        }).then((result) => {
            pageCount.value = result.data
        }).catch((err) => {
            console.info(err)
        });
    }


}
// 部门+人员级联数据
const othwr_List = ref([])

// 把部门树 + 用户合并成 cascader 可用的两级数据
async function buildCascaderOptions(deptTree) {
    const options = []

    // 递归遍历部门
    const walk = async (nodes) => {
        for (const dept of nodes) {
            // 拉当前部门下的用户
            const { data: users } = await axios.get('http://localhost:5181/api/User/GetUsers', {
                params: { dept: dept.dept_id },
                headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
            })

            // 把用户塞进 children
            const children = users.map(u => ({
                value: u.user_name,   // 最终保存入库员名字
                label: u.user_name    // 级联面板显示名字
            }))

            options.push({
                value: dept.dept_id,
                label: dept.dept_name,
                children
            })

            // 如果还有子部门，继续递归
            if (dept.children?.length) {
                await walk(dept.children)
            }
        }
    }

    await walk(deptTree)
    return options
}


function handleSizeChange(val) {
    pageSize.value = val;
    productFill();
}

function handleCurrentChange(val) {
    currentPage.value = val;
    productFill();
}

// 查询计量单位
function getMeasure() {
    axios.get("http://localhost:5181/api/Dict/Get_Dict_Datas", {
        params: {
            dict_type: "db_measure"
        }, headers: {
            authorization: `Bearer ${localStorage.getItem('token')}`
        }
    }).then((result) => {
        measureOptios.value = result.data
        measureOptios.value = [{
            dict_value: "0", dict_label: "请选择单位"
        }, ...result.data]
    }).catch((err) => {
        console.info(err)
    });
}

// 根据计量单位id返回计量单位名称
function measureValue(row) {
    alert
    if (!row) return "无";
    const parentDept = measureOptios.value.find((sex) => sex.dict_value == row);
    return parentDept ? parentDept.dict_label : "无";
}

// 查询产品属性
function getAttribute() {
    axios.get("http://localhost:5181/api/Dict/Get_Dict_Datas", {
        params: {
            dict_type: "db_pro_attribute"
        }, headers: {
            authorization: `Bearer ${localStorage.getItem('token')}`
        }
    }).then((result) => {
        attributeOptios.value = result.data
    }).catch((err) => {
        console.info(err)
    });
}

// 根据产品属性id返回产品属性名称
function attributeValue(row) {
    if (!row) return "无";
    const parentDept = attributeOptios.value.find((sex) => sex.dict_value == row);
    return parentDept ? parentDept.dict_label : "无";
}

// 根据选择条件查询产品库存信息
function productEedit() {
    debounceSearch(() => {
        productFill();
        productCount();
    });
}

// 重置条件查询
function productReaslt() {
    productName.value = ""
    dict_code.value = "0"
    productFill()
    productCount()
}

// 表格选择变化时的处理函数
const handleSelectionChange = (val) => {
    selectedProducts.value = val;
};

// 点击确定存储选择的产品数据
const handleConfirmSelection = () => {
    selectedData.value = [...selectedData.value, ...selectedProducts.value.map(item => ({
        ...item,
        sale_qty: Number(0), // 初始化销售数量为0
        pro_total_amount: Number(0).toFixed(2), // 销售总金额
        pro_total_cost: Number(0).toFixed(2), // 成本合计
        pro_sale_price: Number(item.pro_sale_price || 0).toFixed(2), // 格式化销售单价
        pro_cost_price: Number(item.pro_cost_price || 0).toFixed(2), // 格式化成本单价
    }))] // 保存选择的产品数据
    dialogTableVisible.value = false
    multipleTableRef.value.clearSelection() // 清空当前选择
}

// 表格选择变化时处理数据
const handleSelectedChange = (val) => {
    selectedRows.value = val;
};

// 判断以添加过的产品数据不能再次添加
const isDisabled = (row) => {
    return !selectedData.value.some(item => item.pro_code === row.pro_code);
};

// 退出页面并删除当前页面的标签页
const closeTab = inject('closeTab'); // 注入关闭方法
function handleClose() {
    const targetPath = "/main/Inv/OtherWarehouseReceipts";

    if (closeTab) {
        closeTab(); // 调用父组件提供的关闭方法
    }

    // 添加目标标签页（如果不存在）
    const tabs = inject('editableTabs');
    if (tabs && !tabs.value.some(tab => tab.path === targetPath)) {
        tabs.value.push({
            title: "销售订单",
            name: targetPath,
            path: targetPath
        });
    }

    // 跳转并激活目标标签页
    const activeTab = inject('editableTabsValue');
    if (activeTab) {
        activeTab.value = targetPath;
    }

    router.push(targetPath);
}



// 查询仓库信息
function WeahousesSelect() {
    axios.get("http://localhost:5181/api/Db_warehouse/WarehouseBySelect", {
        headers: {
            'Authorization': 'Bearer ' + localStorage.getItem('token')
        }
    }).then((res) => {
        Weahouse.value = res.data;
    }).catch((res) => {
        console.log(res)
    })
}

onMounted(async() => {
  
   
    getMeasure()
    getAttribute()
    getCustomer()
    productFill()
    productCount()
    getClassify()
    WeahousesSelect()
    getCustomerVender()
    const { data: deptTree } = await axios.get('http://localhost:5181/api/Dept/DeptOpt', {
        headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
    })
    // 2. 拼装级联
    othwr_List.value = await buildCascaderOptions(deptTree)
})
</script>

<style scoped>
.goods-add-form {
    padding: 20px;
    background-color: #fff;
}

.section {
    margin-bottom: 30px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    padding: 20px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.section-title {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 15px;
}

.filter-section {
    margin-bottom: 20px;
    display: flex;
    align-items: center;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
}

.button-group {
    float: right;
    display: flex;
    position: flex;
    text-align: right;
    margin-top: 20px;
    height: 7%;
    align-items: center;
    width: 80.5%;
    background-color: #ffffff;
    justify-content: flex-end;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    padding-right: 20px

}
.fade-enter-active,
.fade-leave-active {
    transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
    opacity: 0;
}


.dialog-footer {
    display: flex;
    justify-content: flex-end;
    padding-top: 15px;
    border-top: 1px solid #ebeef5;
}

.el-table--enable-row-hover .el-table__body tr:hover>td {
    background-color: #f5f7fa !important;
    cursor: pointer;
}



.order-selection-dialog {
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
}

/* 搜索区域样式 */
.dialog-search-area {
  background-color: #f8fafc;
  padding: 16px 20px;
  border-radius: 6px;
  margin-bottom: 16px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.search-input-group {
  display: flex;
  align-items: center;
}

.search-input {
  flex: 1;
  max-width: 320px;
}

/* 表格容器 */
.dialog-table-container {
  border: 1px solid #ebeef5;
  border-radius: 6px;
  padding: 2px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.03);
  margin-bottom: 16px;
}

/* 表头样式 */
.column-header {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
}

/* 日期单元格样式 */
.date-cell {
  font-family: 'Courier New', monospace;
  color: #2c3e50;
  font-weight: 500;
}

/* 分页样式 */
.dialog-pagination {
  display: flex;
  justify-content: center;
  padding: 8px 0;
  background: #f9fbfd;
  border-radius: 6px;
}

/* 底部按钮样式 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  padding-top: 16px;
  border-top: 1px solid #eee;
  margin-top: 8px;
}

/* 行悬停效果 */
.el-table :deep(.el-table__row):hover {
  background-color: #f5f9ff !important;
  cursor: pointer;
}

/* 当前行高亮 */
.el-table :deep(.current-row) {
  background-color: #e6f7ff !important;
}
</style>